import Vue from 'vue'
import VueRouter from 'vue-router'
import home from '../views/home/index.vue'
import welcome from '../views/home/welcome.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  // 定义为home的子路由是因为都是属于home组件下的路由
  {
    path: '/home',
    redirect: '/welcome',
    component: home,
    children: [
      { path: '/welcome', component: welcome }
  
    ]
  },
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
// 为路由对象添加beforeEach导航守卫
// to表示将要访问的路径，from是从哪个页面路径跳转而来的，next表示放行的函数
router.beforeEach((to, from, next) => {
  // 如果用户访问的是登录页面，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage 中获取到保存的token值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token,强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
